// pages/resDetailsghy/resDetailsghy.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarTitle: null,
    titleImgSrcList: [],
    value: null,
    pricePerPerson: null,
    respackageList:[],
    resreviewList:[],
    showAllPacks: false,
    showAllImages: false,
    resAddress: '',
    voucherBought: false,
    userInfo: {},


    addmissage: '选的位置',
    // markers	 Array	标记点
    stitle: '故宫',
    latitude: "",
    longitude: "",
    scale: 14,
    markers: [],
    distanceArr: []
  },

  onClickLeft(){
    wx.navigateBack();
  },

  goToResAllImgs(){
    const titleImgSrcList = this.data.titleImgSrcList;
    const encodedTitleImgSrcList = encodeURIComponent(JSON.stringify(titleImgSrcList));
    wx.navigateTo({
      url: `/pages/resAllImgs/resAllImgs?titleImgSrcList=${encodedTitleImgSrcList}`,
    })
  },

  goToResPackageDetails(e) {
    const packageId = this.data.respackageList[e.currentTarget.dataset.index].packageId;
    console.log("packageId", packageId);
    wx.navigateTo({
      url: `/pages/resPackageDetailsghy/resPackageDetailsghy?packageId=${packageId}`,
    });
  },

  goToResReviewDetails(e){
    const resreviewList = this.data.resreviewList;
    const encodedResreviewList = encodeURIComponent(JSON.stringify(resreviewList));
    wx.navigateTo({
      url: `/pages/resReviewDetailsghy/resReviewDetailsghy?resreviewList=${encodedResreviewList}`,
    })
  },

  showAllPackages() {
    this.setData({
      showAllPacks: !this.data.showAllPacks
    });
  },

  // 点击显示该评论的所有图片
  onImageContainerClick() {
    this.setData({
      showAllImages: !this.data.showAllImages
    });
  },

  // 代金券
  onVoucherBuy() {
    // 检查用户是否登录
    const userInfo = app.globalData.userInfo;
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/pages/login/login' // 如果没登录则直接跳转到登录页面
      });
      return;
    }

    if (!this.data.voucherBought) {
      wx.showToast({
        title: '抢购成功',
        icon: 'success',
        duration: 2000
      });
      this.setData({
        voucherBought: true
      });
    }
  },

  getLocation(e) {
    const address = e.currentTarget.dataset.address;
    
    const mapKey = 'ABKBZ-ZWK67-AWWXM-PTYNQ-R2UE2-ZYFDU'; // 替换为实际Key
    
    // 调用腾讯地图API获取坐标
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      method: 'GET',
      data: {
        address: address,
        key: mapKey
      },
      success: (res) => {
        if (res.data.status === 0) {
          const location = res.data.result.location;
          
          // 打开微信内置地图
          wx.openLocation({
            latitude: location.lat,
            longitude: location.lng,
            name: address,
            scale: 18,
            success: () => console.log('打开地图成功'),
            fail: (err) => console.error('打开地图失败', err)
          })
        } else {
          console.error('地址解析失败:', res.data.message);
          wx.showToast({
            title: '地址解析失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('地图API请求失败', err);
        wx.showToast({
          title: '定位服务异常',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取用户信息
    const userInfo = app.globalData.userInfo;
    this.setData({ userInfo });
    console.log('用户信息:', userInfo);

    const baseUrl = 'http://localhost:8080';

    if (options.resId) {
      const resId = options.resId;
      // 调用后端接口
      wx.request({
        url: 'http://localhost:8080/system/respackage/list', // 替换为实际的接口地址
        method: 'GET', // 根据实际情况修改请求方法
        data: {
          resId: resId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const data = res.data;
            console.log(data);
            this.setData({
              respackageList: data.rows,
            });
            // 检查 respackageList 是否有数据
            if (this.data.respackageList.length > 0) {
              const resName = this.data.respackageList[0].resInfo.resName;
              const resInfoImg = baseUrl + this.data.respackageList[0].resInfo.imgUrl;
              const value = this.data.respackageList[0].resInfo.overallScore;
              const avgPrice = this.data.respackageList[0].resInfo.avgPrice;
              
              // 处理地址拼接，过滤掉 null 或空字符串
              const { province, city, district, address } = this.data.respackageList[0].resInfo;
              const addressParts = [province, city, district, address].filter(part => part && part.trim()!== '');
              const resAddress = addressParts.join('');

              console.log("resInfoImg", resInfoImg);
              this.setData({
                navBarTitle: resName,
                titleImgSrc: resInfoImg,
                value: value,
                pricePerPerson: avgPrice,
                resAddress: resAddress
              });
            }
            // 计算折扣价格
            const respackageList = this.data.respackageList.map(item => {
              const discount = parseFloat(item.discount);
              const unitPrice = parseFloat(item.unitPrice);
              const discountedPrice = (unitPrice * (discount / 10)).toFixed(2);
              return {
                ...item,
                discountedPrice,
                imageUrl: baseUrl + item.imgUrl
              };
            });
            this.setData({
              respackageList
            });
            // 更新 titleImgSrcList
            const titleImgSrcList = respackageList.map(item => item.imageUrl);
            this.setData({
              titleImgSrcList
            });
          } else {
            wx.showToast({
              title: '请求失败',
              icon: 'none',
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none',
          });
        },
      });

      // 调用后端接口获取评论列表
      wx.request({
        url: 'http://localhost:8080/system/resreview/list',
        method: 'GET',
        data: {
          resId: resId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const data = res.data;
            const baseUrl = 'http://localhost:8080';
            console.log(data);
            // 处理每条评论及其图片
            const processedReviews = data.rows.map(review => {
            // 处理头像URL
            review.avatar = baseUrl + review.avatar;
      
              // 处理评论图片列表
              if (review.imgList && review.imgList.length > 0) {
                review.imgList = review.imgList.map(img => ({
                  ...img,
                  imgUrl: baseUrl + img.imgUrl // 拼接完整URL
                }));
              }

              // 去掉 <p></p> 标签
              review.content = review.content.replace(/<p>|<\/p>/g, '');

              return review;
            });
            this.setData({
              resreviewList: data.rows
            });
          } else {
            wx.showToast({
              title: '请求评论数据失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络请求评论数据失败',
            icon: 'none'
          });
        }
      });
    }
    console.log("respackageList:", this.data.respackageList);
    console.log("resreviewList:", this.data.resreviewList);


    var that = this
        //获取当前的地理位置、速度
        wx.getLocation({
            type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function (res) {
                console.log(res);
                //赋值经纬度
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,

                })
                // 发送给朋友、分享朋友圈
                app.onShareAppMessage();
            }
        })
  },

  //导航
  onGuideTap: function (event) {
    var lat = Number(event.currentTarget.dataset.latitude);
    var lon = Number(event.currentTarget.dataset.longitude);
    var bankName = event.currentTarget.dataset.bankname;
    console.log(lat);
    console.log(lon);
    wx.openLocation({
        type: 'gcj02',
        latitude: lat,
        longitude: lon,
        name: bankName,
        scale: 28
    })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})